"""
Python 多线程同步问题 （共享全局变量，资源竞争问题）
"""
import time
import threading


# 线程共享变量
num1 = 0
num2 = 0


class NumIncrement(threading.Thread):
	"""自定义自增线程类"""

	def __init__(self, count):
		super().__init__()
		self.count = count
	
	def run(self):
		self.num_increment()

	def num_increment(self):
		"""数字自增"""
		global num1
		for i in range(self.count):
			num1 += 1


def sync_test():
	"""多线程同步测试"""
	global num1, num2

	print('num1=%d' % num1)
	print('num2=%d' % num2)

	count = 1000
	t1 = NumIncrement(count)
	t2 = NumIncrement(count)

	t1.start()
	t2.start()
	t1.join()
	t2.join()

	# 单线程自增
	for i in range(2):
		for j in range(count):
			num2 += 1

	print('num1=%d' % num1)
	print('num2=%d' % num2)


def main():
	sync_test()


if __name__ == '__main__':
	main()